package com.css.fxfzcpxx.base.attachment.repository.impl;

import com.css.fxfzcpxx.base.attachment.entity.AttachmentRecordEntity;
import com.css.fxfzcpxx.base.attachment.repository.AttachmentRecordRepository;
import com.css.fxfzcpxx.modules.logRecord.entity.SysLog;
import com.css.fxfzcpxx.util.PlatformObjectUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * @Author:
 * @CreateTime: 2023/9/12 10:50
 * @Description:
 */
@Repository
public class AttachmentRecordRepositoryImpl implements AttachmentRecordRepository {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;


    @Override
    public void save(AttachmentRecordEntity attachmentRecord) {
        String sql = "insert into sys_attachment_record(id,attachment_id,download_time,download_count) " +
                "values(:id, :attachmentId, :downloadTime, :downloadCount)";
        SqlParameterSource source = new BeanPropertySqlParameterSource(attachmentRecord);
        namedParameterJdbcTemplate.update(sql, source);

    }

    @Override
    public AttachmentRecordEntity findByAttachmentId(String attachId) {
        String sql="SELECT * FROM sys_attachment_record WHERE download_time::date = current_date and attachment_id='"+attachId+"'";
        AttachmentRecordEntity attachmentRecord=new AttachmentRecordEntity();
        try {
            attachmentRecord = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(AttachmentRecordEntity.class) );
        }catch (Exception exception){
            return null;
        }

        return attachmentRecord;
    }

    @Override
    public void update(String id, Integer downloadCount) {
        String sql = "update sys_attachment_record set download_count = ? where id = ?";
        jdbcTemplate.update(sql,downloadCount,id);
    }

    @Override
    public Integer getTotalPageView() {
        String sql = "select sum(download_count) from sys_attachment_record ";
        Integer total = jdbcTemplate.queryForObject(sql, Integer.class);
        if(PlatformObjectUtils.isEmpty(total)){
            return 0;
        }
        return total;
    }
}
